<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- gutter意思是 列与列之间的距离 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-input placeholder="请输入内容" class="input-with-select" v-model="queryinfo.query">
              <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="grid-content bg-purple-light">
            <el-button type="primary" @click="addDialog=!addDialog">添加用户</el-button>
            <!-- 对话框组件-----添加数据的表单 -->
            <el-dialog title="添加用户" :visible.sync="addDialog" width="50%" @close="addClose">
              <!-- 表单组件 -->
              <el-form label-width="70px" :model="addForm" :rules="addFormRules" ref="addFormRef">
                <el-form-item label="账号" prop="username">
                  <el-input v-model="addForm.username"></el-input>
                </el-form-item>

                <el-form-item label="密码" prop="password">
                  <el-input v-model="addForm.password"></el-input>
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="addForm.email"></el-input>
                </el-form-item>

                <el-form-item label="手机" prop="mobile">
                  <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="addDialog = false">取 消</el-button>
                <el-button type="primary" @click="AdduserList">确 定</el-button>
              </span>
            </el-dialog>

            <!-- 编辑弹框 -->
            <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
              <!-- 编辑表单 -->
              <el-form :model="updateForm" :rules="addFormRules" ref="updateref" label-width="80px">
                <el-form-item label="姓名" prop="username">
                  <el-input v-model="updateForm.username"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="updateForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                  <el-input v-model="updateForm.mobile"></el-input>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="updateuserlist">确 定</el-button>
              </span>
            </el-dialog>
          </div>
        </el-col>
      </el-row>
      <!-- 表格组件 -->
      <el-table :data="userList" border style="width: 100%">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scoped">
            <el-switch
              active-color="#13ce66"
              inactive-color="#dedee6"
              active-value="100"
              inactive-value="0"
              v-model="scoped.row.mg_state"
              @change="changeStatus(scoped.row.id,scoped.row.mg_state,scoped.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作">
          <!-- 编辑 -->
          <template slot-scope="scoped">
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="updateUserListId(scoped.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click="deleteUserList(scoped.row.id)"
            ></el-button>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top-start">
              <el-button
                type="warning"
                icon="el-icon-setting"
                circle
                @click="showSetRoleDialog(scoped.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[2,5, 8, 10]"
        :page-size="2"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 点击分配角色弹出框 -->
      <el-dialog title="分配角色" :visible.sync="rolesDialog" width="40%">
        <p>当前的用户: {{editinfo.username}}</p>
        <br>
        <p>当前的角色: {{editinfo.role_name}}</p>
        <br>
        <p>
          分配新角色:
          <el-select v-model="selectedrolesId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
        <span slot="footer" class="dialog-footer">
          <el-button @click="rolesDialog = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //查询
      total: 0,
      queryinfo: {
        query: "",
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      dialogVisible: false,
      addDialog: false,
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      //   添加的校验规则
      addFormRules: {
        username: [
          { required: true, message: "请输入您的用户名", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入你的密码", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入你的邮箱", trigger: "blur" },
          { type: "email", message: "格式不对", trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入你的手机号", trigger: "blur" },
          {
            pattern: /^1[345789]\d{9}$/,
            message: "目前只支持中国大陆的手机号码"
          }
        ]
      },
      // 回显表单数据
      updateForm: {
        username: "",
        email: "0",
        mobile: ""
      },
      // 分配角色
      rolesDialog: false,
      editinfo: {},
      rolesList: [],
      // 被选中的项
      selectedrolesId: ""
    };
  },
  methods: {
    //   获取数据
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryinfo
      });
      if (res.meta.status != 200)
        return this.$message.error("获取数据列表失败");
      //把获取的数据添加到数据列表中
      this.userList = res.data.users;
      //   一共多少条数据
      this.total = res.data.total;
    },
    // 根据id回显数据
    async updateUserListId(id) {
      this.dialogVisible = !this.dialogVisible;
      const { data: res } = await this.$http.get(`users/${id}`);
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error("回显数据失败");
      this.updateForm = res.data;
    },
    // 确定更改
    updateuserlist() {
      this.$refs.updateref.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `users/${this.updateForm.id}`,
          this.updateForm
        );
        console.log(res)
        this.dialogVisible = false;
        this.getUserList();
        console.log(res);
      });
    },
    //更改用户状态
    async changeStatus(id, type, user) {
      const { data: res } = await this.$http.put(`users/${id}/state/${type}`);
      if (res.meta.status != 200) {
        user.mg_state = !user.mg_state;
        return this.$message.error("用户状态设置失败");
      }
    },
    //关闭弹框的时候清空数据
    addClose() {
      this.$refs.addFormRef.resetFields();
    },
    // 分页
    handleSizeChange(size) {
      this.queryinfo.pagesize = size;
      this.getUserList();
    },
    handleCurrentChange(num) {
      this.queryinfo.pagenum = num;
      this.getUserList();
    },
    //删除数据
    async deleteUserList(id) {
      const result = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(() => {
        return "clac";
      });
      console.log(result);
      if (result == "clac") {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      } else if (result == "confirm") {
        const { data: res } = await this.$http.delete("users/" + id);
        // console.log(res);
        if (!res.meta.status == 200) return this.$message.error("删除失败");
        this.$message.success("删除用户成功");
        this.getUserList();
      }
    },
    // 添加
    AdduserList() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return false;
        const { data: res } = await this.$http.post("users", this.addForm);
        //  console.log(res)
        if (!res.meta.status == 201) return this.$message.error("添加失败");

        this.$message.success("添加成功");
        this.getUserList();
        this.addDialog = false;
      });
    },
    // 点击分配角色弹框
    async showSetRoleDialog(userinfo) {
      this.editinfo = userinfo;
      const { data: res } = await this.$http.get("roles");
      console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表失败！");
      this.rolesList = res.data;
      this.rolesDialog = !this.rolesDialog;
    },
    // 点击按钮 分配角色
    async saveRoleInfo() {
      if (!this.selectedrolesId) return this.$message.error("获取角色列表失败");
      const { data: res } = await this.$http.put(`users/${this.editinfo.id}/role`,{rid: this.selectedrolesId}); 
      console.log(res)
      if(res.meta.status!==200)return this.$message.error("设置角色失败");
      this.$message.success("分配角色成功");
      this.getUserList();
       this.rolesDialog = !this.rolesDialog;
    }
  },

  created() {
    this.getUserList();
  }  
};
</script>

<style lang="less" scoped>
.box-card {
  margin-top: 20px;
}
</style>
